const {AVATAR_ERROR}=require('../error/errorType')
const multer=require('@koa/multer')
const {v4}=require('uuid')
const path=require('node:path')

const upload=multer({
    storage:multer.diskStorage({
        destination:(req,file,cb)=>{
            cb(null,'./uploads')
        },
        filename:(req,file,cb)=>{
            cb(null,v4()+path.extname(file.originalname))
        }
    })
})

const uploadAvatar=upload.single('avatar')

const verifyUploadAvatar=async(ctx,next)=>{
    const {file}=ctx.request
    if(!file){
        return ctx.app.emit('error',new Error(AVATAR_ERROR),ctx)
    }
    ctx.avatarInfo=file
    await next()
}

module.exports={
    uploadAvatar,
    verifyUploadAvatar
}